/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UDP;

import java.io.*;
import java.net.*;

/**
 *
 * @author DongVan
 */
public class Listenner {
        public static void main(String[] args) {
        // TODO code application logic here
        try {
            String stSend;
            String stRcv;
            boolean sExit,rExit;
            int port = 1234 ;  //port socket used to listen
            //khoi tao socket
            DatagramSocket socket=new DatagramSocket(port);
            do{
                //Nhan thong diep tu Client
                byte []rcvbuf = new byte[1024];
                //Tao DatagramPacket de nhan data
                DatagramPacket rcvpkt = new DatagramPacket(rcvbuf,rcvbuf.length);
                //Goi ham nhan DatagramPacket
                socket.receive(rcvpkt);
                stRcv = new String(rcvpkt.getData(),0,rcvpkt.getLength());
                System.out.println("Client: "+ stRcv);

                /******************************************************/

                //Goi thong diep cho Client
                byte []sendbuf=new byte[1024];
                BufferedReader in =new BufferedReader(new InputStreamReader(System.in) );
                System.out.print("Server: ");
                stSend= in.readLine();
                sendbuf = stSend.getBytes();
                //Tao DatagramPacket de goi data
                DatagramPacket sendPacket = new DatagramPacket(sendbuf,sendbuf.length,rcvpkt.getAddress(),rcvpkt.getPort());
                //Goi ham goi DatagramPacket
                socket.send(sendPacket);

                sExit = (stSend.compareTo("Exit") != 0);//exit -> 0 != 0
                rExit = (stRcv.compareTo("Exit") != 0);
            }while(sExit && rExit);
            //dong ket noi
            socket.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }  
}
